<template>
    <!-- imgBox用于存图 -->
    <div id="imgBox" style="width: 100%; height: 100%">
        <!-- mapGroup用于分屏，存图 -->
        <div id="mapGroup">
            <!-- mapContainer用于存放地图 -->
            <div id="mapContainer" class="mapContainer"></div>
        </div>
    </div>
</template>

<script setup>
import { ref, nextTick } from 'vue';
import Map from '@/map/index';
import { getGeoJsonByCode, getAllCity, getNamebyAdcode, getAdcodebyName } from '@/utils/map-geojson/get-geojson';
import html2canvas from 'html2canvas';
import jsonData from './中华人民共和国.json';
import { useMapStoreHook } from '@/store/map';
// 初始化map
const mapStore = useMapStoreHook();
const { olMap, extent } = storeToRefs(mapStore);

let rootCode = ref(''); // 权限地区编码

onMounted(() => {
    initMap();
});

onBeforeUnmount(() => {
    if (olMap.value) {
        // 清理地图资源
        olMap.value.layer.disposeMap();
        // 清理全局引用
        mapStore.setOlMap(null);
    }
});

//初始化地图
const initMap = function () {
    mapStore.setOlMap(new Map('mapContainer'));
    olMap.value.layer.initLayer(); //初始化底图
    mapStore.setExtent(olMap.value.layer.initMaskLayer(jsonData)); //添加遮罩层,并将范围全局化
    olMap.value.layer.fitExtentPadding({
        extent: extent.value, duration: 0
    }); //跳转到遮罩层

    // console.log(getNamebyAdcode('370103'));
    // console.log(getAdcodebyName('济南市'));

    // olMap.value.layer.initBoundaryLayer(getAllCity()); //添加边界
};

let olMap2 = ref(null);
//分屏
const addMap = () => {
    if (olMap2.value) return;
    const div = document.createElement('div');
    div.id = 'olMap2';
    div.className = 'mapContainer';
    const mapGroup = document.querySelector('#mapGroup');
    mapGroup.appendChild(div);

    nextTick(() => {
        const mapView = olMap.value.map.getView();
        olMap2.value = new Map('olMap2', mapView);
        olMap2.value.layer.initLayer(); //初始化底图

        const jsonData = getGeoJsonByCode('370000'); //获取JSON数据

        olMap2.value.layer.initMaskLayer(jsonData); //添加遮罩层
        olMap2.value.layer.initBoundaryLayer(getAllCity()); //添加边界

        setTimeout(() => {
            olMap.value.layer.fitExtentPadding({ extent: extent.value, duration: 700 }); //跳转到遮罩层
        }, 100);
    });
};
//取消分屏
const delMap = () => {
    if (!olMap2.value) return;
    olMap2.value.layer.disposeMap();
    const delElement = document.querySelector('#olMap2');
    const mapGroup = document.querySelector('#mapGroup');
    if (delElement) {
        mapGroup.removeChild(delElement);
    }
    olMap2.value = null;
    setTimeout(() => {
        olMap.value.layer.fitExtentPadding({ extent: extent.value, duration: 700 }); //跳转到遮罩层
    }, 100);
};
//截图
const cutPic = async () => {
    let scale = window.devicePixelRatio; //获取当前缩放比例，避免出现截图范围偏移问题
    // 首先对地图内容map-container进行截图
    let imgBox = document.getElementById('imgBox');
    let mapCanvas = await html2canvas(imgBox, {
        useCORS: true,
        allowTaint: false,
        scale: scale,
        dpi: scale,
        ignoreElements: (element) => {
            // 遍历imgBox下的每个元素节点，截图时忽略指定元素
            if (element.classList.contains('routerContainer')) {
                return true;
            }
        }
    });
    // 获取截图框选的位置和尺寸
    let areaBox = document.getElementById('mapGroup');
    let areaBoxRect = areaBox.getBoundingClientRect();
    // // 根据 areaBox 的位置和尺寸，在 mapCanvas 上裁剪出对应的区域
    let cropCanvas = document.createElement('canvas');
    cropCanvas.width = areaBoxRect.width;
    cropCanvas.height = areaBoxRect.height;
    let cropCtx = cropCanvas.getContext('2d');
    // 将需要裁剪的区域绘制到新的 canvas 上
    cropCtx.drawImage(
        mapCanvas,
        (areaBoxRect.left - imgBox.getBoundingClientRect().left) * scale, // 计算相对偏移
        (areaBoxRect.top - imgBox.getBoundingClientRect().top) * scale,
        areaBoxRect.width * scale,
        areaBoxRect.height * scale,
        0,
        0,
        areaBoxRect.width,
        areaBoxRect.height
    );

    // 触发下载裁剪后的图片
    const link = document.createElement('a');
    link.download = '地图.png';
    link.href = cropCanvas.toDataURL();
    link.click();
};

defineExpose({ addMap, delMap, cutPic });
</script>

<style>
#mapGroup {
    width: 100%;
    height: 100%;
    display: flex;
    flex-wrap: wrap;
}

/* 当有1个元素时 */
#mapGroup:has(.mapContainer:nth-child(1):last-child)>.mapContainer {
    width: 100%;
    height: 100%;
}

/* 当有2个元素时 */
#mapGroup:has(.mapContainer:nth-child(2):last-child)>.mapContainer {
    width: 50%;
    height: 100%;
}

/* 当有3个元素时 */
#mapGroup:has(.mapContainer:nth-child(3):last-child)>.mapContainer:nth-child(-n + 2) {
    width: 50%;
    height: 50%;
}

#mapGroup:has(.mapContainer:nth-child(3):last-child)>.mapContainer:last-child {
    width: 50%;
    height: 50%;
}

/* 当有4个元素时 */
#mapGroup:has(.mapContainer:nth-child(4):last-child)>.mapContainer:nth-child(-n + 2) {
    width: 50%;
    height: 50%;
}

#mapGroup:has(.mapContainer:nth-child(4):last-child)>.mapContainer:nth-child(n + 3) {
    width: 50%;
    height: 50%;
}

/* 当有5个元素时 */
#mapGroup:has(.mapContainer:nth-child(5):last-child)>.mapContainer:nth-child(-n + 3) {
    width: 33.33%;
    height: 50%;
}

#mapGroup:has(.mapContainer:nth-child(5):last-child)>.mapContainer:nth-child(n + 4) {
    width: 33%;
    height: 50%;
}

/* 当有6个元素时 */
#mapGroup:has(.mapContainer:nth-child(6):last-child)>.mapContainer {
    width: 33.33%;
    height: 50%;
}
</style>
